package com.example.music.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.music.R;
import com.example.music.fragment.FavoritesFragment;
import com.example.music.fragment.HomePage;
import com.example.music.fragment.LocalMusicFragment;
import com.example.music.fragment.MyHome;
import com.example.music.fragment.PlaylistDialogFragment;
import com.example.music.fragment.PlaylistFragment;
import com.example.music.fragment.RecentFragment;
import com.example.music.fragment.SongFragment;
import com.example.music.fragment.SongsFragment;
import com.example.music.fragment.UserFragment;
import com.example.music.model.AppConstants;
import com.example.music.model.Song;
import com.example.music.service.MusicService;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

import android.media.MediaMetadataRetriever;

public class MainActivity extends AppCompatActivity implements PlaylistDialogFragment.OnSongSelectedListener{

    private FrameLayout bottomPlayerContainer;
    private ImageView imageView;
    private TextView title;
    private TextView artist;
    private ImageButton btn_play;
    private ImageButton btn_menu;
    private ArrayList<Song> songList;
    private boolean isPlaying;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });


        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnItemSelectedListener(item -> {
            Fragment selectedFragment = null;

            int id = item.getItemId();

            if (id == R.id.item_home) {
                selectedFragment = new HomePage();
            } else if (id == R.id.item_search) {
                selectedFragment = new RecentFragment();
            } else if (id == R.id.item_search) {
                selectedFragment = new FavoritesFragment();
            } else if (id == R.id.item_find) {
                selectedFragment = new LocalMusicFragment();
            } else if (id == R.id.item_mine) {
                selectedFragment = new MyHome();
            }

            if (selectedFragment != null) {
                getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, selectedFragment).commit();
            }

            // 返回 true 表示已处理事件
            return true;
        });

        // 默认加载第一个Fragment
        if (AppConstants.num==0) {
            bottomNavigationView.setSelectedItemId(R.id.item_home);
        }else if (AppConstants.num==1)
        {
            bottomNavigationView.setSelectedItemId(R.id.item_search);
        }else if (AppConstants.num==2)
        {
            bottomNavigationView.setSelectedItemId(R.id.item_find);
        }else
        {
            bottomNavigationView.setSelectedItemId(R.id.item_mine);
        }

        bottomPlayerContainer = findViewById(R.id.bottom_player_container);
        imageView=findViewById(R.id.bo_cover);
        title=findViewById(R.id.bo_title);
        artist=findViewById(R.id.bo_artist);
        btn_menu=findViewById(R.id.bo_menu);
        btn_play=findViewById(R.id.bo_play_pause);


    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        songList=intent.getParcelableArrayListExtra("songList");
        int position=intent.getIntExtra("position",0);
        btn_menu.setOnClickListener(v -> {
            PlaylistDialogFragment dialog = PlaylistDialogFragment.newInstance(songList,position);
            dialog.show(getSupportFragmentManager(), "playlist");
        });
        btn_play.setOnClickListener(v -> {
            Intent serviceIntent = new Intent(this, MusicService.class);
            if(isPlaying)
            {
                btn_play.setImageResource(R.drawable.ic_pause_1);
                serviceIntent.setAction(MusicService.ACTION_PAUSE);
            }
            else {
                btn_play.setImageResource(R.drawable.ic_play_1);
                serviceIntent.setAction(MusicService.ACTION_PLAY);
            }
            isPlaying=!isPlaying;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent);
            } else {
                startService(serviceIntent);
            }
        });

        Song song = (Song) getIntent().getParcelableExtra("song");

        if(song!=null)
        {
            Bitmap albumCover = null;
            try {
                albumCover = getAlbumArt(song.getPath());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            song.setAlbumCover(albumCover);
            boolean is= getIntent().getBooleanExtra("isPlaying",false);
            showMusicPlayer(song.getAlbumCover(),song.getTitle(),song.getArtist(),is);
        }
    }

    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    public void onSongSelected(int posi_1){
        Intent intent = new Intent(this, MusicActivity.class);
        intent.putExtra("position", String.valueOf(posi_1));
        intent.putExtra("songList", new ArrayList<>(songList)); // Pass a copy of the list
        startActivity(intent);
    }

    // 显示播放栏
    public void showMusicPlayer(Bitmap bitmap,String t,String a,boolean isPlaying1) {
        bottomPlayerContainer.setVisibility(View.VISIBLE);
        if(bitmap!=null){
            imageView.setImageBitmap(bitmap);
        }else {
            imageView.setImageResource(R.drawable.default_album_art);
        }
        title.setText(t);
        artist.setText(a);
        if(isPlaying1)
        {
            btn_play.setImageResource(R.drawable.ic_play_1);
        }else {
            btn_play.setImageResource(R.drawable.ic_pause_1);
        }
        isPlaying=isPlaying1;
    }

    // 广播接收器
    private final BroadcastReceiver playStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), AppConstants.ACTION_UPDATE_PLAY_BUTTON)) {
                isPlaying = intent.getBooleanExtra(AppConstants.EXTRA_IS_PLAYING, false);
                int iconResId = isPlaying ? R.drawable.ic_play_1 : R.drawable.ic_pause_1;
                btn_play.setImageResource(iconResId);
            }
        }
    };

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("ActivityStatus", "onResume: 注册广播接收器");
//        // 1. 先读取保存的状态并更新UI
//        SharedPreferences prefs = getSharedPreferences("PlayerPrefs", Context.MODE_PRIVATE);
//        boolean isPlaying1 = prefs.getBoolean(AppConstants.EXTRA_IS_PLAYING, false);
//        int iconResId = isPlaying1 ? R.drawable.ic_play : R.drawable.ic_pause;
//        btnPlayPause.setImageResource(iconResId);
//
//        Log.d("1", String.valueOf(isPlaying1));
        // 2. 注册广播接收器（用于实时更新）
        IntentFilter filter = new IntentFilter(AppConstants.ACTION_UPDATE_PLAY_BUTTON);

        // 动态处理不同API级别
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(
                    playStateReceiver,
                    filter,
                    Context.RECEIVER_EXPORTED  // 改为EXPORTED
            );
        } else {
            registerReceiver(playStateReceiver, filter);
        }

        Log.d("BroadcastDebug", "广播接收器已注册");
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销广播接收器
        Log.d("ActivityStatus", "onPause: 注销广播接收器");
        unregisterReceiver(playStateReceiver);
    }


}